<!--
 * @Author: your name
 * @Date: 2021-04-15 19:43:40
 * @LastEditTime: 2021-05-08 13:52:30
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \PC_Web_Vuee:\FobGoodsData\fob-projects\fobgoods-web-shop\components\FobUpload.vue
-->
<template>
  <div class="vb-upload">
    <el-upload
      action=""
      :file-list="fileList"
      :accept="accept"
      :multiple="multiple"
      :limit="limit"
      :before-upload="beforeUpload"
      :on-exceed="handleExceed"
      :on-change="handleChange"
      :http-request="handleRequest"
      :on-preview="handlePreview"
      :on-success="handleSuccess"
      :on-remove="handleRemove"
      :on-error="handleError"
      :on-progress="handleProgress"
    >
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      <slot name="tip" />

    </el-upload>
  </div>
</template>
<script>
import axios from 'axios'

import dayjs from 'dayjs'
import { getSign } from '@/api/upload'
export default {
  name: 'VbUpload',
  props: {
    value: {
      type: Array,
      default: () => {
        return []
      }
    },
    multiple: {
      type: Boolean,
      default: false
    },
    accept: {
      type: String,
      default: ''
    },
    limit: {
      type: Number,
      default: 1
    },
    readonly: {
      type: Boolean,
      default: false
    },
    max: {
      type: Number,
      default: 0
    },
    // eslint-disable-next-line vue/require-default-prop
    onStart: Function,
    // eslint-disable-next-line vue/require-default-prop
    onProgress: Function,
    // eslint-disable-next-line vue/require-default-prop
    onSuccess: Function,
    // eslint-disable-next-line vue/require-default-prop
    onError: Function,
    // eslint-disable-next-line vue/require-default-prop
    onExceed: Function,
    // eslint-disable-next-line vue/require-default-prop
    // beforeUpload: Function,
    drag: Boolean,
    onPreview: {
      type: Function,
      default() {}
    },
    onRemove: {
      type: Function,
      default() {}
    }

  },
  data() {
    return {
      previewUrl: '',
      showPreview: false
    }
  },
  computed: {
    fileList: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },

  mounted() {

  },
  methods: {
    handleRemove(file, fileList) {
      // const files = JSON.parse(JSON.stringify(this.fileList))
      // files.splice(i, 1)
      console.log('handleRemove-fileList:', file, fileList)
      this.$emit('input', fileList)
    },
    handlePreview(file) {
      window.open(file.url, '_blank')
      console.log('handlePreview:', file)
    },
    handleSuccess(response, file, fileList) {
      console.log('handleSuccess:', response, file, fileList)
    },
    handleError(ex, file, fileList) {
      console.log('handleError:', ex, file, fileList)
    },
    handleProgress(event, file, fileList) {
      console.log('handleProgress:', event, file, fileList)
    },
    handleRequest(option) {
      // return true
      console.log('handleRequest:', option)
      const prom = new Promise((resolve, reject) => {
        const fileType = option.file.name.match(/.[^.]+$/)[0]
        const dir = dayjs().format('YYYYMMDD')
        const name = dayjs().valueOf()
        const filePath = `${process.env.VUE_APP_MINIO_PATH}${dir}/${name}${fileType}`
        getSign({ fileNameList: [filePath] }).then(res => {
          console.log('file:', res)
          const url = res[0]
          axios.put(url, option.file, {
            headers: { 'Content-Type': 'multipart/form-data' }
          }).then(res => {
            //
            const fList = JSON.parse(JSON.stringify(this.value))
            fList.push({
              name: option.file.name,
              url: url.substr(0, url.indexOf('?'))
            })
            console.log('getSign:', fList)

            this.$emit('input', fList)
          }).catch(ex => {
            this.$message.error('上传失败')
          })
        }).catch(ex => {
          this.$message.error('获取签名失败')
        })
      })
      prom.abort = () => {}
      return prom
    },
    beforeUpload(file) {
      console.log(file.type)
      const types = this.accept.split(',')
      const isType = types.length > 0 ? types.includes(file.type) : true
      const isLtSize = this.max > 0 ? (file.size / 1024 / 1024 <= this.max) : true

      if (!isType) {
        this.$message.error('文件格式不对!')
        return false
      }

      if (!isLtSize) {
        this.$message.error(`上传文件大小不能超过 ${this.max} MB!`)

        return false
      }

      return true
    },
    handleChange(file, fileList) {
      console.log('handleChange:', file, fileList, this.fileList)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`最多上传${this.limit}个文件`)
    },
    uploadFiles(files) {
      let postFiles = Array.prototype.slice.call(files)
      if (!this.multiple) { postFiles = postFiles.slice(0, 1) }

      if (postFiles.length === 0) { return }

      this.upload(postFiles)
    }

  }
}
</script>
<style lang="scss">
.vb-upload{
   .el-upload__tip{
    line-height: 1.5;
  }

}
</style>
